from django.views.generic import View
from ..models import CaseResultModel
from ..forms import ReportForm
from utils.messages import Json_Response, Form_Invalid
from utils.paginate import paginate
from utils.record import record
from utils.fmt import datetime_str
from utils.decorators import permission_verify
from copy import deepcopy
import json


class ReportView(View):
    @permission_verify(40005)
    def list(self, request):
        form = ReportForm.List(request)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data.pop('page'), data.pop('page_size')
            qs = CaseResultModel.objects.filter()
            total = qs.count()
            for obj in paginate(qs, page, page_size).values_list(
                    'id', 'set__name', 'status', 'case_num', 'success_num', 'fail_num', 'time_cost',
                    'create_time',
                    named=True
            ):
                result.append({
                    'id': obj.id,
                    'set_name': obj.set__name,
                    'status': {
                        'type': obj.status,
                        'value': CaseResultModel.Status().output(obj.status),
                    },
                    'case_num': obj.case_num,
                    'success_num': obj.success_num,
                    'fail_num': obj.fail_num,
                    'time_cost': obj.time_cost,
                    'create_time': datetime_str(obj.create_time),
                })
            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)

    @permission_verify(40005)
    def details(self, request):
        form = ReportForm.Details(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            result = []
            for obj in CaseResultModel.objects.filter(id=id):
                result = json.loads(obj.result) if obj.result else []

            return Json_Response(msg='查询成功', data=result)
        else:
            return Form_Invalid(form)

    @permission_verify(40006)
    def delete(self, request):
        form = ReportForm.Delete(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            for obj in CaseResultModel.objects.filter(id=id):
                if obj.status == 0:  # 正在执行
                    return Json_Response(code=201, err_msg='任务正在执行,请执行完成后操作')
                copy = deepcopy(obj)
                obj.delete()
                record(request, 12, copy)
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

